package com.bao.work.work03;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author baoye
 * @date 2024-08-13/18:51
 */
public class Test03 {
    public static void main(String[] args) {
        List<Book> books = readXml(new File("day15/src/com/bao/work/work01/bookstore.xml"), Book.class);
        for (Book book : books) {
            System.out.println(book);
        }
    }
    public static<T> List<Book> readXml(File file,Class<T> clazz) {
        if (!file.exists()||!file.isFile()||!file.getName().endsWith(".xml")||!(clazz.isAssignableFrom(Book.class))){
            return null;
        }
        List<Book> bookList = new ArrayList<>();
        Document document = null;
        try {
            document = new SAXReader().read(file);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element rootElement = document.getRootElement();
        List<Element> elements = rootElement.elements();
        for (Element element : elements) {
            String title = element.element("title").getText();
            String author = element.element("author").getText();
            String year = element.element("year").getText();
            String price = element.element("price").getText();
            bookList.add(new Book(title,author,year,Double.parseDouble(price)));;
        }
        return bookList;
    }
}
